#define _CRT_SECURE_NO_WARNINGS 1
#include"string.h"

namespace wjx {

	static const size_t npos = -1;

	void test_string()
	{
		string s1("wjx");
		//string s2 = s1;
		//string::iterator it = s1.begin();
		//s1.push_back('!');
		//cout << s1  << endl;
		//cout << s2;

		s1.append(" wjh");
		cout << s1 << endl;

		s1 += " wjy";
		cout << s1 << endl;

		s1 += '!';
		cout << s1 << endl;
	}
	void string::reserve(size_t n)
	{
		if (n > _capycity)
		{
			char* tem = new char[n+1];
			strcpy(tem, _str);
			delete[] _str;
			_str = tem;
			_capycity = n;
		}
	}
	void string::push_back(char ch)
	{
		if (_size == _capycity)
		{
			reserve(_capycity == 0 ? 4: _capycity * 2);
		}
		_str[_size++] = ch;
	}
	void string::append(const char* str)
	{
		size_t tm = strlen(str);
		if (_size+tm >= _capycity)
		{
			reserve(_size + tm > 2 * _capycity ? _size + tm+1 : 2 * _capycity);
		}
		strcpy(_str + _size, str);
		_size += tm;
	}
	string& string::operator+=(char ch)
	{

		push_back(ch);
		return *this;
	}
	string& string::operator+=(const char* str)
	{
		append(str);
		return *this;
	}
	void string::insert(size_t pos, char ch)
	{
		assert(pos < _size);

		size_t end = _size + 1;
		/*if (_size == _capycity)
		{
			char* trm = new char[2 * _capycity];
			strcpy(trm, _str);
			delete[] _str;
			_str = trm;
			_capycity = 2 * _capycity;
		}*/
		if (_size == _capycity)
		{
			reserve(_capycity == 0 ? 4 : _capycity * 2);
		}
		while (end != pos)
		{
			_str[end] = _str[end - 1];
			end--;
		}
		_str[pos] = ch;
		_size++;
		
	}
	void string::insert(size_t pos, const char* str)
	{
		assert(pos < _size);

		size_t tm = strlen(str);
		size_t end = tm + _size;
		reserve(strlen(str) + _size > 2 * _capycity ? strlen(str) + _size : 2 * _capycity);

		while (end != pos)
		{
			_str[end] = _str[end - tm];

			end--;
		}
		strcpy(_str + pos, str);
		_size += strlen(str);
	}
	void string::erase(size_t pos, size_t len)
	{
		assert(pos < _size);

		if (len >= _size-pos)
		{
			_str[pos] = '\0';
			_size = pos;
		}
		else
		{
			for (size_t i = pos + len; i <= _size; i++)
			{
				_str[i - len] = _str[i];
			}

			_size -= len;
		}
	}
	ostream& operator<<(ostream& out, string& s1)
	{
		/*string::iterator it = s1.begin();
		while (it != s1.end())
		{
			out << *it++;
		}
		out << endl;*/
		for (auto ch : s1)
		{
			out << ch;
		}
		return out;
	}
	/*istream& operator<<(istream& in, string s1)
	{
		in << s1.c_str();
		return in;
	}*/
}